package main

import (
	"basic-go/syntax/webook/internal/repository"
	"basic-go/syntax/webook/internal/repository/cache"
	"basic-go/syntax/webook/internal/repository/dao"
	"basic-go/syntax/webook/internal/service"
	"basic-go/syntax/webook/internal/service/sms/localsms"
	"basic-go/syntax/webook/internal/web"
	"basic-go/syntax/webook/internal/web/middleware"
	"basic-go/syntax/webook/pkg/ginx/middleware/ratelimit"
	"github.com/gin-contrib/cors"
	"github.com/gin-contrib/sessions"
	redissession "github.com/gin-contrib/sessions/redis"
	"github.com/gin-gonic/gin"
	"github.com/redis/go-redis/v9"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"strings"
	"time"
)

func main() {

	server := InitWebServer()
	server.Run(":8080")

}

func initWebServer2() *gin.Engine {
	server := gin.Default()
	// 解决跨域问题
	server.Use(cors.New(cors.Config{
		//AllowAllOrigins:  []string{"http://localhost:3000"},
		AllowCredentials: true,
		AllowHeaders:     []string{"Content-Type", "authorization"},
		// 这个是允许前端访问你的后端响应中带的头部
		ExposeHeaders: []string{"x-jwt-token"},
		AllowOriginFunc: func(origin string) bool {
			if strings.HasPrefix(origin, "http://localhost") {
				return true
			}
			return strings.Contains(origin, "your_company.com")
		},
		MaxAge: 12 * time.Hour,
	}), func(ctx *gin.Context) {
		//println("这是我的Middleware")
	})

	//设置限流 调用的已经实现好的ratelimit插件
	cmd := redis.NewClient(&redis.Options{
		Addr:     "192.168.3.117:6379",
		Password: "",
		DB:       1,
	})
	server.Use(ratelimit.NewBuilder(cmd, time.Minute, 100).Build())

	//UseSession(server)
	UseJWT(server)
	return server
}

func initDB() *gorm.DB {
	db, err := gorm.Open(mysql.Open("root:tyjt#123@tcp(192.168.3.117:3306)/webook?charset=utf8&parseTime=True&loc=Local"))
	if err != nil {
		panic(err)
	}
	err = dao.InitTable(db)
	if err != nil {
		panic(err)
	}
	return db
}

func initUser(server *gin.Engine, db *gorm.DB) {
	ud := dao.NewGormUserDAO(db)
	cmd := redis.NewClient(&redis.Options{
		Addr:     "192.168.3.117:6379",
		Password: "",
		DB:       1,
	})
	userC := cache.NewRedisUserCache(cmd)
	uCache := cache.NewRedisCodeCache(cmd)

	ur := repository.NewUserRepository(ud, userC)
	uCacheR := repository.NewCacheCodeRepository(uCache)

	sms := localsms.NewService()
	us := service.NewUserService(ur)
	codeS := service.NewcodeService(uCacheR, sms)

	c := web.NewUserHandler(us, codeS)
	c.RegisterRoutes(server)
}

func UseJWT(server *gin.Engine) {
	mBuilder := middleware.NewLoginJWTMiddlewareBuilder()
	server.Use(mBuilder.CheckLoginJWT())
}

func UseSession(server *gin.Engine) {
	//store := cookie.NewStore([]byte("secret"))
	// 使用redis存储 session
	store, err := redissession.NewStore(100,
		"tcp",
		"192.168.3.117:6379",
		"",
		[]byte("FNnpVHWjB6TnZ3V2"),
		[]byte("FNnpVHWjB6TnZ3V2"))
	if err != nil {
		panic(err)
	}
	server.Use(sessions.Sessions("mysession", store))
	// 登录校验
	//login := middleware.NewLoginMiddlewareBuilder()
	println("请求经过了这里")
	//server.Use(login.CheckLogin)
}
